<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Admin\Http\Requests\RoleRequest;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|Response|\Illuminate\View\View
     */
    public function index()
    {
        $roles = Role::query()->where('name', '<>', config('hd_module.webmaster'))->orderBy('id', 'desc')->get();
        return view('admin::role.index', compact('roles'));
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|Response
     */
    public function store(RoleRequest $request)
    {
        Role::create(['title' => $request->title, 'name' => $request->name]);
        session()->flash('success', '角色添加成功');
        return back();
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|Response
     */
    public function update(RoleRequest $request, Role $role)
    {
        $role->update(['title' => $request->title, 'name' => $request->name]);
        session()->flash('success', "角色修改成功");
        return back();
    }

    /**
     * @Notes:    删除角色
     * @Interface:          destroy
     * @param Role $role
     * @return:             \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     * @author:             Jokenzhang
     * @Time:               2020/12/18  7:01 下午
     */
    public function destroy(Role $role)
    {
        $role->delete();
        return redirect('/admin/role')->with('success', '删除成功！');
    }

    public function permission(Role $role)
    {
        $modules = \HDModule::getPermissionByGuard('admin');
        return view('admin::role.permission', compact('role', 'modules'));
    }

    public function permissionStore(Request $request, Role $role)
    {
        $role->syncPermissions($request->name);
        session()->flash('success', '权限配置成功');
        return back();
    }
}
